package com.xxxx.server.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码
 */

@RestController
public class CaptchaController验证码 {
    @Autowired
    private DefaultKaptcha defaultKaptch;

    @ApiOperation(value = "验证码")
    // produces：在接口文档中显示图片
    @GetMapping(value = "/captcha",produces="image/jpeg")
    public void captcha(HttpServletRequest request, HttpServletResponse response){
        // 第一步： 配置 响应头 的信息.  是为了通过流的形式 传输 图片。Stream-->outputStream
        //定义response输出类型为Imag/jpeg类型
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, mustrevalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");
        //-------------------第二步：生成验证码 begin --------------------------
        //业务逻辑：
        //第一：生成验证码的文本内容
        String text = defaultKaptch.createText();
        System.out.println("为了方便快速演示，打印验证码："+text);
        // 将验证码放入session中
        request.getSession().setAttribute("captcha",text);
        //第二： 生成验证码的图片
        BufferedImage image = defaultKaptch.createImage(text);
        ServletOutputStream outputStream = null;
        try{
            outputStream = response.getOutputStream();
            //第三步： 用流，进行输出图片，
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            if(null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //-------------------生成验证码 end --------------------------
    }
}
